﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Linq;
using LogLib;
using System.IO;
using KXmlUIControl;
using KeyboardArg;

namespace KWindow.KPageCore
{
    /// <summary>
    /// 专用于TextBox文字映射键值(代码)
    /// 通常在网络传输中，字段的值用代码代替文字含义
    /// 因此此类应运而生，专用于用户查找编辑框文字内容关键字指向的代码
    /// </summary>
    public class TextMapService
    {
        protected Dictionary<string, KeyBoardArgs> TextBoxBindings = null;

        protected List<TextBox> TextBoxs = null;

        private Dictionary<string, string> dicKeyValues = new Dictionary<string, string>();
        public Dictionary<string, string> TextMap
        {
            get 
            {
                Dictionary<string, string> dic = new Dictionary<string, string>();
                foreach (KeyValuePair<string, string> p in dicKeyValues)
                {
                    if (!string.IsNullOrEmpty(p.Key) && !string.IsNullOrEmpty(p.Value))
                    {
                        dic.Add(p.Key, p.Value);
                    }                    
                }
                return dic;
            }
        }

        public TextMapService(List<TextBox> tbs, Dictionary<string, KeyBoardArgs> bindings)
        {
            TextBoxs = tbs;
            TextBoxBindings = bindings;
        }

        public void UpdateData(List<TextBox> tbs, Dictionary<string, KeyBoardArgs> bindings)
        {
            TextBoxs = tbs;
            TextBoxBindings = bindings;
        }

        public void ClearData()
        {
            dicKeyValues.Clear();
        }

        public string this[string key]
        {
            get
            {
                if (dicKeyValues.ContainsKey(key))
                {
                    return dicKeyValues[key];
                }
                else
                {
                    return "";
                }
            }
            set 
            {
                if (dicKeyValues.ContainsKey(key))
                {
                    dicKeyValues[key] = value;
                }
                else
                {
                    dicKeyValues.Add(key, value);
                }
            }
        }

        public void UpdateMapDic()
        {
            foreach (TextBox tb in TextBoxs)
            {
                string text = tb.Text;
                if (string.IsNullOrEmpty(text))
                {
                    continue;
                }
                KeyBoardArgs arg = TextBoxBindings[tb.Name];
                if (!string.IsNullOrEmpty(arg.DictionaryFileName))
                {                 
                    string langCode = arg.LanguageCode;
                   
                    // 获得字典文件的路径
                    string dictionaryFile = string.Format("{0}\\SoftKeyBoard\\DIC\\{1}\\{2}.xml",
                        Application.StartupPath,
                        langCode,
                        arg.DictionaryFileName);
                    if (File.Exists(dictionaryFile))
                    {
                        string code = FindValue(text, dictionaryFile);
                        if (!string.IsNullOrEmpty(code))
                        {
                            if (!dicKeyValues.ContainsKey(arg.Key))
                            {
                                dicKeyValues.Add(arg.Key, code);
                            }
                            else
                            {
                                dicKeyValues[arg.Key] = code;
                            }
                        }                       
                    }
                }              
            }
        }

        /// <summary>
        /// 从字典文件中查找关键字的键值(代码)
        /// </summary>
        /// <param name="tb"></param>
        /// <returns></returns>
        private string FindValue(string key, string dicFile)
        {
            XDocument xmlDoc = XDocument.Load(dicFile);
            XElement root = xmlDoc.Element("root");
            string value = FindElementValueByKey(root, key);
            if (!string.IsNullOrEmpty(value))
            {
                Log.Write("查找成功:" + value);
                return value;
            }
            else
            {
                Log.Write("查找失败.");
                return "";
            }
        }

        /// <summary>
        /// 从XML节点中递归查找符合条件元素的节点
        /// 支持多级父节点省略的模糊查找
        /// </summary>
        /// <param name="root"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        private string FindElementValueByKey(XElement root, string key)
        {
            if (!root.HasElements)
            {
                return "";
            }
            string childItem = "";
            if (ExistsInChildElements(root, key, out childItem))
            {
                int start = key.IndexOf(childItem);
                if (start >= 0 && !key.Equals(childItem))
                {
                    key = key.Remove(start, childItem.Length);
                }
            }
            IEnumerable<XElement> elist = from e in root.Elements()
                                          where e != null
                                          && e.Attribute("key") != null
                                          && key.Equals(e.Attribute("key").Value)
                                          select e;

            if (elist.GetEnumerator() != null && elist.Count() > 0)
            {
                XElement elem = elist.First();
                return elem.Attribute("value").Value;
            }
            foreach (XElement child in root.Elements())
            {
                string result = FindElementValueByKey(child, key);
                if (!string.IsNullOrEmpty(result))
                {
                    return result;
                }
                else
                {
                    continue;
                }
            }
            return "";
        }

        private bool ExistsInChildElements(XElement root, string key, out string childItem)
        {
            childItem = "";
            if (root == null || !root.HasElements)
            {
                return false;
            }
            IEnumerable<string> elist = from e in root.Elements()
                                          where e != null
                                          && e.Attribute("key") != null                                       
                                          select e.Attribute("key").Value;
            if (elist.GetEnumerator() == null || elist.Count() == 0)
            {
                return false;
            }
            foreach (string item in elist)
            {
                if (key.Contains(item))
                {
                    childItem = item;
                    return true;
                }              
            }
            return false;
        }
    }
}


    /// <summary>
        /// 从XML节点中递归查找符合条件元素的节点
        /// </summary>
        /// <param name="root"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        //private string FindElementValueByKey(XElement root, string key)
        //{
        //    if (!root.HasElements)
        //    {
        //        return "";
        //    }

        //    IEnumerable<XElement> elist = from e in root.Elements()
        //                                  where e != null
        //                                  && e.Attribute("key") != null
        //                                  && key.Equals(e.Attribute("key").Value)
        //                                  select e;

        //    if (elist.GetEnumerator() != null && elist.Count() > 0)
        //    {
        //        XElement elem = elist.First();
        //        return elem.Attribute("value").Value;
        //    }
        //    foreach (XElement child in root.Elements())
        //    {
        //        string result = FindElementValueByKey(child, key);
        //        if (!string.IsNullOrEmpty(result))
        //        {
        //            return result;
        //        }
        //        else
        //        {
        //            continue;
        //        }
        //    }
        //    return "";
        //}